<template>
  <div class="report-executions">
    <el-card>
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input v-model="filters.search" placeholder="搜索报表名称" clearable>
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="filters.status" placeholder="执行状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="运行中" value="RUNNING" />
              <el-option label="成功" value="SUCCEEDED" />
              <el-option label="失败" value="FAILED" />
              <el-option label="已取消" value="CANCELED" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-date-picker v-model="filters.dateRange" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
          </el-col>
          <el-col :span="8" class="filter-actions">
            <el-button type="primary" @click="loadExecutions">筛选</el-button>
            <el-button @click="clearFilters">清除</el-button>
          </el-col>
        </el-row>
      </div>

      <el-table :data="executions" style="width: 100%" v-loading="loading">
        <el-table-column prop="report_name" label="报表" />
        <el-table-column prop="status" label="状态" width="110">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)" size="small">{{ statusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="started_at" label="开始时间" width="180">
          <template #default="{ row }">{{ formatTime(row.started_at) }}</template>
        </el-table-column>
        <el-table-column prop="finished_at" label="结束时间" width="180">
          <template #default="{ row }">{{ row.finished_at ? formatTime(row.finished_at) : '-' }}</template>
        </el-table-column>
        <el-table-column prop="duration_ms" label="耗时(ms)" width="120" />
        <el-table-column prop="row_count" label="行数" width="120" />
        <el-table-column label="输出" width="180">
          <template #default="{ row }">
            <el-link v-if="row.output_uri" :href="row.output_uri" target="_blank" type="primary">下载</el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="错误信息">
          <template #default="{ row }">
            <el-tooltip v-if="row.error_message" effect="dark" :content="row.error_message" placement="top">
              <span class="error-ellipsis">{{ row.error_message }}</span>
            </el-tooltip>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { reportApi } from '@/api/report'
import type { ReportExecution, ReportExecutionStatus } from '@/types'
import { Search } from '@element-plus/icons-vue'

const executions = ref<ReportExecution[]>([])
const loading = ref(false)

const filters = ref<{ search: string; status: '' | ReportExecutionStatus; dateRange: string[] | undefined }>({
  search: '',
  status: '',
  dateRange: undefined
})

const loadExecutions = async () => {
  loading.value = true
  try {
    const res = await reportApi.getExecutions()
    let items = res.data.items
    if (filters.value.search) {
      const s = filters.value.search.toLowerCase()
      items = items.filter(i => i.report_name?.toLowerCase().includes(s))
    }
    if (filters.value.status) {
      items = items.filter(i => i.status === filters.value.status)
    }
    // 简单时间范围过滤
    if (filters.value.dateRange && filters.value.dateRange.length === 2) {
      const [start, end] = filters.value.dateRange
      items = items.filter(i => {
        const t = i.started_at
        return t >= start && t <= end
      })
    }
    executions.value = items
  } catch (e) {
    console.error(e)
    ElMessage.error('加载执行历史失败')
  } finally {
    loading.value = false
  }
}

const clearFilters = () => {
  filters.value = { search: '', status: '', dateRange: undefined }
  loadExecutions()
}

const statusText = (s: ReportExecutionStatus) => ({
  RUNNING: '运行中',
  SUCCEEDED: '成功',
  FAILED: '失败',
  CANCELED: '已取消',
  PENDING: '排队中'
}[s] || s)

const statusTagType = (s: ReportExecutionStatus): 'success' | 'warning' | 'danger' | 'info' => ({
  SUCCEEDED: 'success',
  RUNNING: 'warning',
  FAILED: 'danger',
  CANCELED: 'info',
  PENDING: 'info'
}[s] as 'success' | 'warning' | 'danger' | 'info' || 'info')

const formatTime = (t?: string) => (t ? new Date(t).toLocaleString('zh-CN') : '-')

onMounted(loadExecutions)
</script>

<style scoped>
.report-executions {
  padding: 0;
}
.filter-section {
  margin-bottom: 12px;
  padding: 10px 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.filter-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: flex-end;
}
.error-ellipsis {
  display: inline-block;
  max-width: 360px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style> 